package controller;

import entity.User;
import service.UserService;
import util.UserSessionManager;
import view.AdminView;
import view.UserView;

import java.util.Scanner;

public class UserController {
    private final UserService userService = new UserService();
    private UserView userView;
    private AdminView adminView;

    public void setUserView(UserView userView) {
        this.userView = userView;
    }
    public void setAdminView(AdminView adminView) {
        this.adminView = adminView;
    }

    Scanner scanner = new Scanner(System.in);

    public void register() {
        System.out.print("请输入用户名: ");
        String userName = scanner.nextLine();

        String role;
        if(userName.equals("admin")) {
            role = "admin";
        }else{
            role = "user";
        }

        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        if(userService.register(userName, password, role)){
            System.out.println("注册成功！");
        }else{
            System.out.println("用户名已存在！注册失败！");
        };
    }

    public void login() {
        System.out.print("请输入用户名: ");
        String userName = scanner.nextLine();

        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        if(userService.login(userName, password)!=null){
            System.out.println("登录成功！");
        }else{
            System.out.println("用户名或密码错误！登录失败！");
            return;
        };

        User currentUser = userService.login(userName, password);
        UserSessionManager.getInstance().setCurrentUser(currentUser);//获取当前用户的登录信息
        if(currentUser.getRole().equals("admin")){
            adminView.showAdminView();
        }else{
            userView.showUser();
        }
    }

    public void logout() {
        UserSessionManager.getInstance().logout();
    }

    public void viewProfile(int userId) {
        User user = userService.getUserById(userId);
        System.out.println("个人信息：");
        System.out.println("用户名: " + user.getUserName());
        System.out.println("注册时间: " + user.getCreatedTime());
    }
}

